import requests
import json
import uuid
from django.http import JsonResponse
from django.shortcuts import redirect
from django.contrib.auth import get_user_model
from .JWTTool import jwtTool
from Login.models import ThirdPartyLogin

User = get_user_model()

# 飞书 OAuth 配置 - 修复回调地址
FEISHU_APP_ID = "cli_a859e9e114ae100b"
FEISHU_APP_SECRET = "o6EqyfEJ6mXCubbTMQ48rbxiQjdTRafR"
FEISHU_REDIRECT_URI = "http://localhost:8000/oauth/feishu/callback"  # 修复：使用正确的飞书回调地址
FEISHU_AUTH_URL = "https://open.feishu.cn/open-apis/authen/v1/authorize"
FEISHU_TOKEN_URL = "https://open.feishu.cn/open-apis/authen/v1/access_token"
FEISHU_USER_URL = "https://open.feishu.cn/open-apis/authen/v1/user_info"

class FeishuOAuth:
    @staticmethod
    def get_authorize_url(state=None):
        """生成飞书授权URL"""
        if not state:
            state = str(uuid.uuid4())
        
        # 尝试不使用scope参数，或者使用更基础的权限
        params = {
            'app_id': FEISHU_APP_ID,
            'redirect_uri': FEISHU_REDIRECT_URI,
            'response_type': 'code',
            'state': state
            # 暂时移除scope参数，看看是否能解决20043错误
        }
        
        # 构建URL
        url = f"{FEISHU_AUTH_URL}?" + "&".join([f"{k}={v}" for k, v in params.items()])
        return url, state
    
    @staticmethod
    def get_access_token(code):
        """用授权码换取访问令牌"""
        data = {
            'grant_type': 'authorization_code',
            'code': code,
            'app_id': FEISHU_APP_ID,
            'app_secret': FEISHU_APP_SECRET,
            'redirect_uri': FEISHU_REDIRECT_URI
        }
        
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        
        try:
            response = requests.post(FEISHU_TOKEN_URL, json=data, headers=headers)
            print(f"Token response status: {response.status_code}")
            print(f"Token response: {response.text}")
            
            if response.status_code == 200:
                result = response.json()
                if result.get('code') == 0:
                    return result.get('data')
                else:
                    print(f"Token error: {result}")
            return None
        except Exception as e:
            print(f"Token request error: {e}")
            return None
    
    @staticmethod
    def get_user_info(access_token):
        """获取用户信息"""
        headers = {
            'Authorization': f'Bearer {access_token}',
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        
        try:
            response = requests.get(FEISHU_USER_URL, headers=headers)
            print(f"User info response status: {response.status_code}")
            print(f"User info response: {response.text}")
            
            if response.status_code == 200:
                result = response.json()
                if result.get('code') == 0:
                    return result.get('data')
                else:
                    print(f"User info error: {result}")
            return None
        except Exception as e:
            print(f"User info request error: {e}")
            return None
    
    @staticmethod
    def handle_callback(request):
        """处理飞书登录回调"""
        code = request.GET.get('code')
        state = request.GET.get('state')
        
        print(f"Callback received - code: {code}, state: {state}")
        
        if not code:
            return JsonResponse({'error': '授权失败'}, status=400)
        
        try:
            # 获取访问令牌
            token_data = FeishuOAuth.get_access_token(code)
            if not token_data:
                return JsonResponse({'error': '获取访问令牌失败'}, status=400)
            
            access_token = token_data.get('access_token')
            refresh_token = token_data.get('refresh_token')
            expires_in = token_data.get('expires_in')
            
            print(f"Access token: {access_token}")
            
            # 获取用户信息
            user_info = FeishuOAuth.get_user_info(access_token)
            if not user_info:
                return JsonResponse({'error': '获取用户信息失败'}, status=400)
            
            print(f"User info: {user_info}")
            
            # 修改：使用user_id而不是open_id
            feishu_user_id = str(user_info.get('user_id'))
            username = user_info.get('name')
            email = user_info.get('email')
            avatar = user_info.get('avatar_url')
            
            # 查找或创建用户
            user, created = User.objects.get_or_create(
                username=f"feishu_{feishu_user_id}",
                defaults={
                    'email': email or f"{feishu_user_id}@feishu.cn",
                    'first_name': username or '',
                }
            )
            
            # 保存第三方登录信息
            third_party_login, _ = ThirdPartyLogin.objects.get_or_create(
                platform='feishu',
                platform_user_id=feishu_user_id,
                defaults={
                    'user': user,
                    'access_token': access_token,
                    'refresh_token': refresh_token,
                    'platform_user_info': user_info
                }
            )
            
            # 生成JWT token
            jwt_token = jwtTool.generate_token(user.id)
            
            # 重定向到前端，携带token
            frontend_url = f"http://localhost:5173/home?token={jwt_token}"
            return redirect(frontend_url)
            
        except Exception as e:
            print(f"Callback error: {e}")
            return JsonResponse({'error': f'登录处理失败: {str(e)}'}, status=500)
